package com.lge.clock.worldclock;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

import android.content.Context;
import android.graphics.Color;
import android.graphics.Typeface;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckedTextView;
import android.widget.ImageView;
import android.widget.LinearLayout;

import android.widget.TextView;

import com.lge.clock.R;
import com.lge.clock.worldclock.cities.CityInformation;
/* LGSI_CHANGE_S: Alarm
 * 2012.04.16,prajna.dalei@lge.com,
 * Number conversion in Worldclock
 */
import com.lge.clock.util.CommonUtil;
/* LGSI_CHANGE_E: Alarm*/


/**
 * @author lge.com
 */
public class WorldClockAdapter extends ArrayAdapter<CityInformation> {
	private int mResource;
//	private boolean isAcEnable = true;
//	private boolean isDelete = false;
	private long sysOffset = 0;
	private Context mContext;
	private String mFromWidget;
	
	private LinearLayout mListItemMain;
	private CheckedTextView mCheckBox;
	private TextView mAmView;
	private TextView mHourView;
	private TextView mMinuteView;
	private TextView mPmView;
	private LinearLayout mLineView;
	private TextView mCityNameView;
	private TextView mCityDateView;
	private LinearLayout worldclockDigitClock;
	private ImageView mDstIcon;
        private Typeface typeface;

	/**
	 * suein1209.kim
	 * TAG
	 */
	private final static String TAG = "WorldClockAdapter";
	
	/**
	 * suein1209.kim
	 * Default font path
	 */
	private final static String DEFAULT_FONT_PATH = "/system/fonts/DroidSans.ttf";
	
	/**
	 * Constructor for WorldClockAdapter.
	 */
	public WorldClockAdapter(Context context, int textViewResourceId,
			ArrayList<CityInformation> items) {
		super(context, textViewResourceId, items);
		this.mContext = context;
		this.mResource = textViewResourceId;
                typeface = Typeface.createFromFile(DEFAULT_FONT_PATH);
	}
	
	public WorldClockAdapter(Context context, int textViewResourceId,
			ArrayList<CityInformation> items, String fromWidget) {
		super(context, textViewResourceId, items);
		this.mContext = context;
		this.mResource = textViewResourceId;
		this.mFromWidget = fromWidget;
                typeface = Typeface.createFromFile(DEFAULT_FONT_PATH);
	}
	
//	public void setClockVisible(boolean isA) {
//		isAcEnable = isA;
//	}
//	
//	public boolean getClockVisible() {
//		return isAcEnable;
//	}
//	
//	public void setDelete(boolean isD) {
//		isDelete = isD;
//	}
	
	public void setSystemOffset(long system_offset) {
	    sysOffset = system_offset;
	}
	
	/**
	 * Method getView.
	 * @see android.widget.Adapter#getView(int, View, ViewGroup) */
	public View getView(int position, View convertView, ViewGroup parent) {
		
		final CityInformation item = getItem(position);
		final long currentTime = getCurrentTime(item);
		
		/*init View*/
		LinearLayout wcView = makeChildItemView(convertView);

		/*set initialized widget parameter in BG*/
		setInitWidgetInBG(wcView);
		
		/*set delete check button*/
//		setDeleteCheckBtn(item.getChecked());
		
		// check item and delete
		mCheckBox = (CheckedTextView)wcView.findViewById(R.id.CheckBox);
		if(mCheckBox != null)
			mCheckBox.setChecked(item.getChecked());

		/*set displayed date string*/
                /* LGSI_CHANGE_S: Alarm
                 * 2012.04.16,prajna.dalei@lge.com,
                 * Number conversion in Worldclock
                 */
		if(CommonUtil.isArabFarsiLanguage())
		    mCityDateView.setText(CommonUtil.convertArabFarsiNum(getDateFormatFromDate(currentTime),false));
		else
/* LGSI_CHANGE_E: Alarm*/
		    mCityDateView.setText(getDateFormatFromDate(currentTime));
        
        /* Date String (use 24H or not)*/
		Calendar calendar = new GregorianCalendar();
		calendar.setTimeInMillis(currentTime);
		
		boolean timeFormat = DateFormat.is24HourFormat(mContext);
        mHourView.setText(getHourStringFromCalendarDate(timeFormat, calendar));
        mMinuteView.setText(getMinuteStringFromCalendarDate(calendar));
		
        /*set City name With Country name*/
        setCityNameWithCountry(item.getCityName(), item.getCountryName(), item.getDuplicated());

		/*daylight saving configuration is set by user.*/
		setVisibleDST(item.getSummerTime());
		
		/*WTF!!!!*/
		//digitClockCheck();
		
		return wcView;
		
	} //End Of Method getView

	/**
	 * suein1209.kim
	 * 
	 * init covertView object
	 * @param convertView
	 */
	private LinearLayout makeChildItemView(View convertView) {
		LinearLayout ret = null;
		
		if(convertView == null) {
			Context tempContext = getContext();
			ret = new LinearLayout(tempContext);
			LayoutInflater vi = (LayoutInflater)tempContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			vi.inflate(mResource, ret, true);
		} else {
			ret = (LinearLayout) convertView;
		} //End of if
		
		return ret;
	} //End Of Method getinitedCovertView
	
	/**
	 * suein1209.kim
	 * 
	 * set initialized widget parameter in BG
	 * @param wcView
	 */
	private void setInitWidgetInBG(View wcView) {
		mListItemMain = (LinearLayout)wcView.findViewById(R.id.List_Item_Main);

		// digital clock
		mAmView = (TextView)wcView.findViewById(R.id.DClockAm);
		mHourView = (TextView)wcView.findViewById(R.id.DClockHour);
		mMinuteView = (TextView)wcView.findViewById(R.id.DClockMinute);
		
		mPmView = (TextView)wcView.findViewById(R.id.DClockPm);
		
		mLineView = (LinearLayout)wcView.findViewById(R.id.DClock_line);
		mLineView.setVisibility(View.VISIBLE);
		
		//added by essin@lge.com 2010.12.31 because font issue!
		mHourView.setTypeface(typeface);
		mMinuteView.setTypeface(typeface);
		// city info
		mCityNameView = (TextView)wcView.findViewById(R.id.cityName);
		mCityNameView.setSelected(true); // marquee needs
		mCityDateView = (TextView)wcView.findViewById(R.id.cityDate);
		
		worldclockDigitClock = (LinearLayout)wcView.findViewById(R.id.DigitalClock);

		//daylight saving configuration is set by user.
		mDstIcon = (ImageView)wcView.findViewById(R.id.dstIcon);
		
	} //End Of Method setInitWidgetInBG
	
	

	/**
	 * seuin1209.kim
	 * 
	 * set DST Visible or Not
	 * @param dst
	 */
	private void setVisibleDST(int dst) {
		if(dst > 0) { 
			mDstIcon.setVisibility(View.VISIBLE);
			mDstIcon.setImageResource(R.drawable.sumersavingtime);
			
		} else{
			mDstIcon.setVisibility(View.GONE);
			
		} //End Of if(dst > 0)
	} //End Of Method setVisibleDST

	/**
	 * suein1209.kim
	 * 
	 * set City name With Country name
	 * @param cityName
	 * @param countryName
	 * @param isDuplicated
	 */
	private void setCityNameWithCountry(String cityName, String countryName, boolean isDuplicated) {
		if(isDuplicated) {
            String cityNameWithContury;
            cityNameWithContury = cityName + " (" + countryName + ")";
            mCityNameView.setText(cityNameWithContury);
            
        }else {
            mCityNameView.setText(cityName);
            
        } //End Of if(isDuplicated) {
		
	} //End Of Method setCityNameWithCountry

	/**
	 * suein1209.kim
	 * 
	 * get minute string from claendar date
	 * @param calendar
	 * @return
	 */
	private String getMinuteStringFromCalendarDate(Calendar calendar) {
		return String.format("%02d", calendar.get(Calendar.MINUTE));
		
	} //End Of Method getMinuteStringFromCalendarDate

	/**
	 * suein1209.kim
	 * Get Hour String (Use 24H or not) 
	 * @param timeFormat
	 * @param calendar
	 * @return
	 */
	private String getHourStringFromCalendarDate(boolean timeFormat, Calendar calendar) {
		
		String RetHourStr = "N/A";
		if (timeFormat == true) {
			
			// [junehyuk.jang] START Change Worldclock list UI
			boolean ret = setWorldCockBacgroundConfig(timeFormat, calendar);
			if(!ret){
				Log.e(TAG, "Exception : Fail the Set WorldClock Backgoround");
				/*Any Thing to DO*/
			}//End Of if
			
			RetHourStr = String.format("%02d", calendar.get(Calendar.HOUR_OF_DAY));
			// [junehyuk.jang] END Change WorldClock list UI
		}
        else {
        	
        	boolean ret = setWorldCockBacgroundConfig(timeFormat, calendar);
			if(!ret){
				Log.e(TAG, "Exception : Fail the Set WorldClock Backgoround");
				/*Any Thing to DO*/
			}//End Of if
			
			int mHour = calendar.get(Calendar.HOUR);
			RetHourStr = mHour == 0 ? "12" : String.valueOf(mHour); 
                        /* LGSI_CHANGE_S: Alarm
                         * 2012.04.16,prajna.dalei@lge.com,
                         * Number conversion in Worldclock
                         */
			if(CommonUtil.isArabFarsiLanguage()){
                            RetHourStr=CommonUtil.convertArabFarsiNum(RetHourStr,false);
                       }
                      /* LGSI_CHANGE_E: Alarm*/			
        } //End Of if (timeFormat == true)
		return RetHourStr;
		
	} //End Of Method getHourStringFromCalendarDate

	/**
	 * suein1209.kim
	 * 
	 * Set Background Value in World Digit Clock
	 * @param drawable
	 * @param textColor
	 */
	private void setBackgroundValue(int drawable, int textColor, int AmViewVisible, int PmViewVisible, boolean timeFormat) {
		mAmView.setVisibility(AmViewVisible);
		mPmView.setVisibility(PmViewVisible);
		
		//[haesun.jung][WBT#310906] 2012.01.24
		if(worldclockDigitClock != null)
			worldclockDigitClock.setBackgroundResource(drawable);
		
		mHourView.setTextColor(textColor);
		mMinuteView.setTextColor(textColor);
		
		/*if not use 24Hour*/
		if(!timeFormat){
			mAmView.setTextColor(textColor);
			mPmView.setTextColor(textColor);
		}
		
	} //End of Method setBackgroundValue
	
	/**
	 * suein1209.kim
	 * 
	 * Set Bacground Config
	 * @param timeFormat
	 * @param calendar
	 * @return
	 */
	private boolean setWorldCockBacgroundConfig(boolean timeFormat, Calendar calendar) {
		
		final int textColorValue = 0xff16304e;
		if (worldclockDigitClock != null) {
			
			if(timeFormat){
				/*if use 24 Hour*/
				int mHour = calendar.get(Calendar.HOUR_OF_DAY);
				
				if (mHour > 5 && mHour < 18) {
					setBackgroundValue(R.drawable.worldclock_clock, textColorValue, View.GONE, View.GONE, timeFormat);
					
				} else {
					setBackgroundValue(R.drawable.worldclock_clock_pm, Color.WHITE, View.GONE, View.GONE, timeFormat);
					
				}//End Of if
				
			}else{
				/*if not use 24 Hour*/
				int mHour = calendar.get(Calendar.HOUR);
//			    if(mHour == 0)
//                {
//                	mHour += 12;
//                }
				boolean isAM = calendar.get(Calendar.AM_PM) == Calendar.AM;
				
				if(isAM && (mHour > 5 && mHour < 12)){
					mAmView.setText(R.string.sp_AM_string_NORMAL);
					setBackgroundValue(R.drawable.worldclock_clock, textColorValue, View.VISIBLE, View.GONE, timeFormat);
						
				}else if(isAM && !(mHour > 5 && mHour < 12)){
					mAmView.setText(R.string.sp_AM_string_NORMAL);
					setBackgroundValue(R.drawable.worldclock_clock_pm, Color.WHITE, View.VISIBLE, View.GONE, timeFormat);
					
				}else if(!isAM && (mHour > 5 && mHour < 12)){
					mPmView.setText(R.string.sp_PM_string_NORMAL);
					setBackgroundValue(R.drawable.worldclock_clock_pm, Color.WHITE, View.GONE, View.VISIBLE, timeFormat);
					
				}else if(!isAM && !(mHour > 5 && mHour < 12)){
					mPmView.setText(R.string.sp_PM_string_NORMAL);
					setBackgroundValue(R.drawable.worldclock_clock, textColorValue, View.GONE, View.VISIBLE, timeFormat);
					
				} //End Of if (calendar.get(Calendar.AM_PM) == Calendar.AM)
				
			} //End Of if(timeFormat)
			
			//return set result true
			return true;
		}else{
			
			//return set result false
			return false;
		}//End Of if
		
	} //End Of Method setWorldCockBacgroundConfig
	
	/**
	 * suein1209.kim
	 * 
	 * Get Current time from millSec
	 * @param item
	 * @return
	 */
	private long getCurrentTime(CityInformation item) {
		int dst = item.getSummerTime();
		long diffGmt = item.getGmtValue() + (3600000 * dst);
		long currentTime = java.lang.System.currentTimeMillis() + (diffGmt - sysOffset);
		return currentTime;
		
	} //End Of Method getCurrentTime
	
	/**
	 * suein1209.kim
	 * 
	 * set Delete check button
	 * @param isChecked
	 */
//	private void setDeleteCheckBtn(boolean isChecked) {
//		if(isDelete == true) {
//			mCheckBox.setVisibility(View.VISIBLE);
//			mCheckBox.setImageResource(isChecked == true ? R.drawable.btn_check_on : R.drawable.btn_check_off);
//			
//		} else {
//			mCheckBox.setVisibility(View.GONE);
//			
//		} //End Of if(isDelete == true)
//		
//	} //End Of Method setDeleteCheckBtn

	/**
	 * suein1209.kim
	 * 
	 * Get Simple Date Foramt
	 * @param currentTime
	 * @return
	 */
	private String getDateFormatFromDate(long currentTime) {
		SimpleDateFormat sdf = new SimpleDateFormat(mContext.getResources().getString(R.string.date_format));
		Date date = new Date(currentTime);
		return sdf.format(date);
		
	} //End of Method getDateForamtFromDate


}
